package cn.coisini.security.exception;

import cn.coisini.model.common.enums.ResultEnum;
import cn.coisini.utils.ExceptionUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @author xiangshaw
 * Description: 当未登录或者token失效访问接口时，自定义的返回结果
 */
@Component
public class RestAuthenticationPoint implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authentication) throws IOException {
        // 获取请求状态
        int status = response.getStatus();
        ResultEnum resultEnum;
        if (status == HttpServletResponse.SC_NOT_FOUND){
            // 请求路径不存在
            resultEnum = ResultEnum.DATA_NOT_EXIST;
        }else if (authentication instanceof BadCredentialsException){
            // 账号密码错误
            resultEnum = ResultEnum.LOGIN_USERNAME_OR_PASSWORD_ERROR;
        }else {
            // 其他异常
            resultEnum = ResultEnum.TOKEN_INVALID;
        }
        ExceptionUtil.handleException(response, resultEnum);
    }
}